package com.aizuda.boot.modules.business.feishu.strategy;

import com.aizuda.boot.config.properties.FeiShuConfigProperties;
import com.aizuda.boot.modules.auth.domain.entity.ThirdUser;
import com.aizuda.boot.modules.business.feishu.domain.AtUsersDTO;
import com.aizuda.boot.modules.business.feishu.domain.BotValues;
import com.aizuda.boot.modules.system.entity.SysMessage;
import com.aizuda.core.api.ApiAssert;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.Optional;

/**
 * @Author aizuda
 * @ClassName FeishuConfigStrategy
 * @Description 飞书配置策略服务类，根据tenantKey动态获取飞书配置信息
 * @Version 1.0
 * @Date 2025/7/11
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FeishuConfigStrategy {

    private final FeiShuConfigProperties feiShuConfigProperties;

    /**
     * 根据tenantKey获取飞书应用配置
     *
     * @param tenantKey 租户Key
     * @return 飞书应用配置
     */
    public FeiShuConfigProperties.FeiShuAppConfig getConfigByTenantKey(String tenantKey) {
        ApiAssert.isEmpty(tenantKey, "租户Key不能为空");
        ApiAssert.isEmpty(feiShuConfigProperties.getApps(), "飞书应用配置未初始化");

        Optional<FeiShuConfigProperties.FeiShuAppConfig> configOptional = feiShuConfigProperties.getApps()
                .values()
                .stream()
                .filter(config -> tenantKey.equals(config.getTenantKey()))
                .findFirst();

        if (configOptional.isEmpty()) {
            log.error("未找到tenantKey为{}的飞书应用配置", tenantKey);
            throw new RuntimeException("未找到对应的飞书应用配置，tenantKey: " + tenantKey);
        }

        FeiShuConfigProperties.FeiShuAppConfig config = configOptional.get();
        log.info("成功获取tenantKey为{}的飞书应用配置，应用名称：{}", tenantKey, config.getName());

        return config;
    }


    public FeiShuConfigProperties.FeiShuTemplateConfig getTemplateConfig(FeiShuConfigProperties.FeiShuAppConfig appConfig, String businessType) {
        if (null == appConfig || CollectionUtils.isEmpty(appConfig.getTemplates())) {
            log.warn("没有配置飞书应用");
            return null;
        }
        Optional<FeiShuConfigProperties.FeiShuTemplateConfig> templateConfig = appConfig.getTemplates().values()
                .stream()
                .filter(template -> template.getBusinessScope().contains(businessType))
                .findFirst();
        if (templateConfig.isEmpty()) {
            log.error("未找到对应的模版配置");
            return null;
        }
        FeiShuConfigProperties.FeiShuTemplateConfig feiShuTemplateConfig = templateConfig.get();
        log.info("获取模版配置:{}", feiShuTemplateConfig);
        return feiShuTemplateConfig;
    }

    public BotValues buildBotValues(Map<String, Object> map, ThirdUser thirdUser, FeiShuConfigProperties.FeiShuTemplateConfig templateConfig) {
        if (!map.containsKey("type")){
            return null;
        }
        String businessType = map.get("type").toString();
        BotValues botValues = new BotValues();
        botValues.setOpenId(thirdUser.getOpenId());
        botValues.setTenantKey(thirdUser.getTenantKey());
        botValues.setBusinessType(businessType);
        templateConfig.getTemplateParams().forEach(item ->{
            if (item.equals("type")){
                botValues.addParam(item, getMessageTypeDescription(businessType));
                return;
            }
            if (map.containsKey(item)){
                botValues.addParam(item, map.get(item));
            }
        });

        return botValues;
    }


    /**
     * 根据业务类型获取消息类型描述
     */
    protected String getMessageTypeDescription(String businessType) {
        if (null == businessType) {
            return "文本";
        }
        return switch (businessType) {
            case "flowTodoTask" -> "流程待处理提醒";
            case "filling" -> "归档提醒";
            case "performance" -> "合同到期提醒";
            case "at" -> "@提醒";
            case "remind" -> "催办提醒";
            default -> "提醒";
        };
    }
} 